import sys
from you_get import common as you_get
import os

def mkdir(path):
    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")
    # 判断路径是否存在# 存在 True# 不存在 False
    isExists = os.path.exists(path)
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录 # 创建目录操作函数
        os.makedirs(path) 
        print(path + ' 创建成功')
        return True
    else:
        # 如果目录存在则不创建，并提示目录已存在
        print(path + ' 目录已存在')
        return False

def get_all(cwd,result): 
    get_dir = os.listdir(cwd)  
    for i in get_dir:          
        sub_dir = os.path.join(cwd,i)  
        if os.path.isdir(sub_dir):     
            get_all(sub_dir)
        else:
            result.append(i)
    return result

def download_video(url_path,video_downpath):
    print('url_path=',url_path)
    f0=open(url_path,'r+',encoding='utf-8')
    url_all=f0.readlines()
    for k in range(0,len(url_all)):
        print('正在载入到',video_downpath)
        url = url_all[k].replace('\n','')
        print('正在下载视频',url)
        sys.argv = ['you-get','-o',video_downpath,url]  #sys传递参数执行下载，就像在命令行一样
        you_get.main()
    f0.close()

path='G:/代码/python/B站视频抓取/B站视频抓取/'
filename=[]
urldir='./URL/'
get_all(urldir,filename)
for i in filename:
    url_path=path+'URL/'+i
    video_downpath=path+'视频抓取/'+(i.replace('.txt','',1))+'/'
    mkdir(video_downpath)
    print(url_path)
    print('视频将会下载至：'+video_downpath)
    download_video(url_path,video_downpath)